# encoding: UTF-8
import socket
import thread


# socket.send,recv,accept默认是同步的
class SimpleChatclient():
    def __init__(self, host, port):
        self.cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
        self.cli.connect((host, port));
        self.handler_started = False;
    
    def run(self):
        try:
            while 1:
                buf = raw_input("> : ")
                print "send : " + str(buf)
                self.cli.send(buf)
                if not self.handler_started:
                    self.handler_started = True
                    thread.start_new_thread(self.recv_handler, ())
        except Exception, e:
            print "error : " , e
            self.cli.close()
            thread.exit_thread()
            
    def recv_handler(self):
        try:
            while 1:
                buf = self.cli.recv(1024)
                print 'received : ', buf
        except Exception, e:
            print "error : ", e
            self.cli.close()
            thread.exit_thread()
        

SimpleChatclient('127.0.0.1', 8002).run()
